package niit.group5.app;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;

public class Level1 extends View implements SurfaceHolder.Callback {

	private int balID = 0; // variable to know what ball is being dragged
	Bitmap mbackground, frame;
	Paint paint, paint_prgs_bg, paint_prgs;
	private Map<Integer, ObjectsDraw> arr_Do_vat = new HashMap<Integer, ObjectsDraw>();
	Map<Integer, Object[]> arr_Info_Do_vat = new HashMap<Integer, Object[]>();
	// luu diem
	private int score = 0;
	private int MAX_SCORE = 40;
	private Thread gameThread;
	private int TIME_GAME_LEVEL_1 = 15;
	private Handler handler;
	int count = 0;

	public Level1(Context context) {
		super(context);
		setFocusable(true); // necessary for getting the touch events
		// getHolder().addCallback(this);
		mbackground = BitmapFactory.decodeResource(getResources(),
				R.drawable.level1_bg);

		frame = BitmapFactory.decodeResource(getResources(), R.drawable.frame);

		// cai dat danh sach cac do vat va toa do ban dau, toa do dat cua vat
		arr_Info_Do_vat.put(1, new Object[] { 80, 340, R.drawable.dv_gau, 288,
				200, 350, 520 });
		arr_Info_Do_vat.put(2, new Object[] { 160, 380, R.drawable.rubic, 288,
				200, 350, 520 });
		arr_Info_Do_vat.put(3, new Object[] { 290, 390, R.drawable.dv_dep, 288,
				200, 350, 520 });
		arr_Info_Do_vat.put(4, new Object[] { 400, 370, R.drawable.dv_goi, 288,
				200, 350, 520 });
		arr_Info_Do_vat.put(5, new Object[] { 60, 35, R.drawable.dv_anh, 300,
				500, 350, 520 });

		buildListDo_vat(context);
		paint = new Paint();
		paint_prgs_bg = new Paint();
		paint_prgs = new Paint();
		handler = new Handler();
		gameThread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (count < 180) {

					try {
						gameThread.sleep(1000);
						count += 10;
						postInvalidate();

					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
				handler.post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (count > 180) {
							gameThread.stop();
							if (score < MAX_SCORE) {
								GameLoader.isGameOver = true;
							}
						}
					}
				});

			};

		});
		gameThread.start();

	}

	private void buildListDo_vat(Context context) {
		int index = 1;
		// Cai dat toa do cac do vat
		for (Map.Entry do_vat : arr_Info_Do_vat.entrySet()) {
			Object[] infor = (Object[]) do_vat.getValue();
			Point point = new Point();
			point.x = ((Integer) infor[0]).intValue();
			point.y = ((Integer) infor[1]).intValue();

			// declare each ball with the ColorBall class
			arr_Do_vat.put(index, new ObjectsDraw(context, ((Integer) infor[2])
					.intValue(), point));
			index++;
		}
	}

	// the method that draws the balls
	@Override
	protected void onDraw(Canvas canvas) {
		// canvas.drawColor(0xFFCCCCCC); //if you want another background color
		Rect dest = new Rect(0, 0, getWidth(), getHeight());
		canvas.drawBitmap(mbackground, null, dest, paint);
		canvas.drawBitmap(frame, 0, 0, paint);
		paint.setTextSize(10);

		canvas.drawRect(288, 200, 350, 320, paint);
		canvas.drawText("Score : " + score, 30, 18, paint);
		canvas.drawText("Time : ", 150, 18, paint);
		paint_prgs_bg.setColor(Color.DKGRAY);
		canvas.drawRect(190, 13, 370, 22, paint_prgs_bg);
		paint_prgs.setColor(Color.GREEN);
		canvas.drawRect(190, 13, 370 - count, 22, paint_prgs);
		// draw the balls on the canvas
		for (Map.Entry objDraw : arr_Do_vat.entrySet()) {
			ObjectsDraw do_vat = (ObjectsDraw) objDraw.getValue();
			canvas.drawBitmap(do_vat.getBitmap(), do_vat.getX(), do_vat.getY(),
					null);
		}

	}

	// events when touching the screen
	public boolean onTouchEvent(MotionEvent event) {
		int eventaction = event.getAction();

		int X = (int) event.getX();
		int Y = (int) event.getY();

		switch (eventaction) {

		case MotionEvent.ACTION_DOWN: // touch down so check if the finger is on
			// a ball
			// balID = 0;
			balID = 0;
			for (Map.Entry objDraw : arr_Do_vat.entrySet()) {
				ObjectsDraw do_vat = (ObjectsDraw) objDraw.getValue();

				// check if inside the bounds of the ball (circle)
				// get the center for the ball
				// int centerY = do_vat.getY() + 15;

				int centerX = do_vat.getX() + do_vat.getBitmap().getWidth() / 2;
				int centerY = do_vat.getY() + do_vat.getBitmap().getHeight()
						/ 2;

				// calculate the radius from the touch to the center of the ball
				double radCircle = Math
						.sqrt((double) (((centerX - X) * (centerX - X)) + (centerY - Y)
								* (centerY - Y)));
				// if the radius is smaller then 23 (radius of a ball is 22),
				// then it must be on the ball

				if (radCircle <= do_vat.getBitmap().getWidth() / 2
						|| radCircle <= do_vat.getBitmap().getHeight() / 2) {
					balID = do_vat.getID();

					break;
				}

				// check all the bounds of the ball (square)
				// if (X > ball.getX() && X < ball.getX()+50 && Y > ball.getY()
				// && Y < ball.getY()+50){
				// balID = ball.getID();
				// break;
				// }
			}

			break;

		case MotionEvent.ACTION_MOVE: // touch drag with the ball
			// move the balls the same as the finger
			if (balID > 0 && arr_Do_vat.size() >= balID) {
				arr_Do_vat.get(balID).setX(X - 15);
				arr_Do_vat.get(balID).setY(Y - 15);
			}

			break;

		case MotionEvent.ACTION_UP:
			if (balID > 0) {
				ObjectsDraw do_vat = (ObjectsDraw) arr_Do_vat.get(balID);
				if (do_vat != null) {
					int centerX = do_vat.getX() + do_vat.getBitmap().getWidth()
							/ 2;
					int centerY = do_vat.getY()
							+ do_vat.getBitmap().getHeight() / 2;
					int pos_Start_X, pos_Start_Y = 0;
					int pos_End_X, pos_End_Y = 0;
					if (arr_Info_Do_vat.containsKey(balID)) {
						Object[] obj = arr_Info_Do_vat.get(balID);
						pos_Start_X = Integer.valueOf((Integer) obj[3]);
						pos_Start_Y = Integer.valueOf((Integer) obj[4]);
						pos_End_X = Integer.valueOf((Integer) obj[5]);
						pos_End_Y = Integer.valueOf((Integer) obj[6]);

						// touch drop - just do things here after dropping
						// check all the bounds of the ball (square)
						if (centerX > pos_Start_X && centerY > pos_Start_Y
								&& centerX < pos_End_X && centerY < pos_End_Y) {
							score += 10;
							arr_Info_Do_vat.remove(balID);
							arr_Do_vat.remove(balID);

							break;
						} else {
							arr_Do_vat.get(balID).setX(
									Integer.valueOf((Integer) obj[0]));
							arr_Do_vat.get(balID).setY(
									Integer.valueOf((Integer) obj[1]));
						}
					}
				}
				balID = 0;
			}
			break;

		}
		// redraw the canvas
		invalidate();
		return true;

	}

	@Override
	public void onWindowFocusChanged(boolean hasWindowFocus) {
		// if (!hasWindowFocus)
		// gameThread.wait();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		// gameThread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		boolean retry = true;
		while (retry) {
			try {
				gameThread.join();
				retry = false;
			} catch (InterruptedException e) {
			}
		}
	}
}
